import { classPrefix } from '../../variables';
import { useEffect, useState } from 'react';

interface Options {
    pick?: string[], // 支持仅剩的一些
    filter?: string[], // 排除一些
    default?: object, // 组件自己的默认值
}

const globalDefault = {
    'font-size': 'm',
    'size': 'm',
    'font-color': 'm',
    'color': 'm',
};
const standardClassesMap = {};
const standardClasses = `
    font-size size line-height font-color color bg-color border-color border-radius 
    margin margin-top margin-left margin-right margin-bottom 
    paddding paddding-top paddding-left paddding-right paddding-bottom`.split(/\s/g).filter(s => s);
standardClasses.forEach((className) => {
    standardClassesMap[className] = 1;
});

export default (uiConfig, options: Options = {} ) => {
    const [resClasses, setResClasses] = useState([]);
    const [uiString, setUiString] = useState(JSON.stringify(uiConfig));
    // 控制变化
    JSON.stringify(uiConfig) !== uiString && setUiString(JSON.stringify(uiConfig));
    useEffect(() => {
        const defaultStyles = { ...(options.default || {}), ...globalDefault };
        let allowUsedMap = {};
        let resClasses = [];
        if (options.pick) {
            options.pick.forEach((className) => {
                if (standardClassesMap[className]) allowUsedMap[className] = 1;
            });
        } else if (options.filter) {
            standardClasses.forEach((className) => {
                if (!options.filter.includes(className)) allowUsedMap[className] = 1;
            });
        } else {
            allowUsedMap = standardClassesMap;
        }
        standardClasses.forEach((className) => {
            if (allowUsedMap[className] && (defaultStyles[className] || uiConfig[className])) {
                resClasses.push(`${classPrefix}-${className}-${uiConfig[className] || defaultStyles[className]}`);
            }
        });
        setResClasses(resClasses);
    }, [uiString]);

    return resClasses.join(' ');
};
